#!/use/bin/python
# coding=utf-8
# 统计 助眠功能 引流来源统计
import datetime
import pymysql
import requests
import json

from dbutils.pooled_db import PooledDB

# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur


#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X * 100 / Y, 2)
    return rate

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql):
    conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    return num

# 统计助眠功能引流来源
def zmgnSourceCount():
    try:
        conn, cur = getDataConnection()
        #判断 获取各个来源的数据量
        sjtxNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.key ='saEnterPage' and JSON_EXTRACT(t.msg,'$.from')= 'unknown'")
        homeNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.key ='saEnterPage' and JSON_EXTRACT(t.msg,'$.from')= 'home'")

        logDetail = f"{today}日新增-来自睡觉提醒的数量为{sjtxNum},来自app主页的数量为{homeNum}"
        print(logDetail)
        # 报表key
        analysisKey = "zmgnSourceCount"
        saveJsonDb(analysisKey, 'sjtx', '睡觉提醒', sjtxNum, today)
        saveJsonDb(analysisKey, 'home', 'app首页', homeNum, today)
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()
#助眠来源点击率
def zmgnSourceClickRate():
    try:
        conn, cur = getDataConnection()
        #判断 获取各个来源的数据量
        sjtxSourceNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.key ='saEnterPage' and JSON_EXTRACT(t.msg,'$.from')= 'unknown'")
        homeSourceNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.key ='saEnterPage' and JSON_EXTRACT(t.msg,'$.from')= 'home'")
        #获取睡觉提醒 提醒次数
        sjtxEnterNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'srShowResult'  and JSON_EXTRACT(msg,'$.result') =1")
        #睡觉提醒点击率
        sjtxClickRate = getRateByXY(sjtxSourceNum,sjtxEnterNum)

        # 获取进入APP首页次数
        homeEnterNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'homePageShow' ")
        # APP主页点击率
        homeClickRate = getRateByXY(homeSourceNum, homeEnterNum)

        logDetail = f"{today}日新增-来自睡觉提醒的数量为{sjtxSourceNum},睡觉提醒提醒次数为{sjtxEnterNum},点击率为{sjtxClickRate}," \
                    f"来自app主页的数量为{homeSourceNum},进入app主页次数为{homeEnterNum},点击率为{homeClickRate}"
        print(logDetail)
        # 报表key
        analysisKey = "zmgnSourceClickRate"
        saveJsonDb(analysisKey, 'sjtx', '睡觉提醒', sjtxClickRate, today)
        saveJsonDb(analysisKey, 'home', 'app首页', homeClickRate, today)
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


def saveJsonDb(analysisKey,fieldKey,fieldName,fieldValue,refDate):
    try:
        conn, cur = getDataConnection()
        countNum = selectNumBySql(
            f"select count(1) from analysis_dynamic t where 1=1 and  t.ref_date = '{refDate}' and t.analysis_key = '{analysisKey}' and  JSON_EXTRACT(t.msg,'$.field_key') ='{fieldKey}'")
        msgDict = {}
        msgDict["field_key"] = fieldKey
        msgDict["field_name"] = fieldName
        msgDict["field_value"] = fieldValue
        msgJson = json.dumps(msgDict, ensure_ascii=False, sort_keys=False, separators=(',', ':'))

        if countNum == 0:
            # 插入
            insertSql = f"""insert into analysis_dynamic(analysis_key,msg,ref_date) 
                            value('{analysisKey}','{msgJson}','{refDate}')"""
            cur.execute(insertSql)
        else:
            updateSql = f"""update analysis_dynamic set msg = '{msgJson}',update_time = now()  where 1=1 and  ref_date = '{refDate}' and analysis_key = '{analysisKey}' and  JSON_EXTRACT(msg,'$.field_key') ='{fieldKey}'"""
            cur.execute(updateSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

#如 2022年12月13号 获取 221213 作为分表后缀
def getdateyyMMdd(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    re_date = re_date[2:]
    return re_date

if __name__ == '__main__':
    d = 1
    today = getdate(d)
    yyMMddDate = getdateyyMMdd(d)
    zmgnSourceCount()
    zmgnSourceClickRate()